package com.dinglicom.walktourmap;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKOfflineMap;
import com.baidu.mapapi.MKOfflineMapListener;
import com.baidu.mapapi.MKPlanNode;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.TransitOverlay;
import com.dinglicom.walktourmap.logic.DistanceOverlay;
import com.dinglicom.walktourmap.logic.IDistanceListener;
import com.dinglicom.walktourmap.logic.LocusOverlayT;
import com.dinglicom.walktourmap.logic.MeLocationOverlay;
import com.dinglicom.walktourmap.ui.OfflineMapActivity;
import com.dinglicom.walktourmap.utils.ImageUtil;

public class BMap_Distance extends MapActivity implements OnClickListener,
		LocationListener, MKSearchListener, MKOfflineMapListener,
		IDistanceListener {

	private static String TAG = "andli";

	/**
	 * 位置管理对象
	 */
	private MKLocationManager mLocationManager;

	/**
	 * 地图View
	 */
	private MapView mapView;

	/**
	 * 弹出PopView对象
	 */
	private View popupView;

	/**
	 * 地图控制对象
	 */
	private MapController mapController;

	/**
	 * 地图搜索对象
	 */
	private MKSearch mkSearch;

	/**
	 * 离线地图管理对象
	 */
	private MKOfflineMap mkOfflineMap;

	/**
	 * 当前位置对象
	 */
	private GeoPoint locationGeoPoint;

	/**
	 * 我的位置覆盖物
	 */
	private MyLocationOverlay myLocationOverlay;

	/**
	 * 轨迹重绘对象
	 */
	private LocusOverlayT locusOverlayItem;

	private ImageButton navButton;

	private ImageButton hokeyBtn;

	/**
	 * 搜索框
	 */
	private TextView searchTV;

	/**
	 * 定位按钮
	 */
	private ImageButton mylocBtn;

	/**
	 * 放大地图比例
	 */
	private ImageButton zoomUpBtn;

	/**
	 * 缩放地图比例
	 */
	private ImageButton zoomDownBtn;

	/**
	 * 显示交通流量按钮
	 */
	private ToggleButton trafficTbn;

	/**
	 * 截屏按钮
	 */
	private ImageButton screenshotBtn;

	/**
	 * PopView 对象
	 */
	private TextView locationName;

	private TextView locationAddress;

	/**
	 * 测距PopView
	 */
	private PopupWindow distancePopView;

	private Button distanceBtn;

	private ImageButton delMarkBtn;

	private ImageButton delAllMarkBtn;

	private MenuItem distanceMenuItem;

	/**
	 * 搜索PopView
	 */
	private PopupWindow searchPopView;

	private AutoCompleteTextView startAutoComleteTV;

	private AutoCompleteTextView endAutoComleteTV;

	private ImageButton searchBtn;

	private DistanceOverlay mDistanceOverlay;// 测距覆盖层

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bmap_distance);
		findView();
		initMap();
	}

	/**
	 * 初始化控件<BR>
	 * [功能详细描述]
	 */
	public void findView() {
		mapView = (MapView) findViewById(R.id.mapView);
		navButton = (ImageButton) findViewById(R.id.ImageButtonNav);
		hokeyBtn = (ImageButton) findViewById(R.id.ImageButtonHotkey);
		searchTV = (TextView) findViewById(R.id.TextViewSearch);
		mylocBtn = (ImageButton) findViewById(R.id.ImageButtonMyloc);
		zoomUpBtn = (ImageButton) findViewById(R.id.ImageButtonZoomUp);
		zoomDownBtn = (ImageButton) findViewById(R.id.ImageButtonZoomDown);
		trafficTbn = (ToggleButton) findViewById(R.id.ToggleButton_ITS);
		screenshotBtn = (ImageButton) findViewById(R.id.ImageButtonAR);
		// 构建PopupView
		popupView = super.getLayoutInflater().inflate(R.layout.popup, null);
		locationName = (TextView) popupView.findViewById(R.id.locationName);
		locationAddress = (TextView) popupView
				.findViewById(R.id.locationAddress);
		locationName.setText(R.string.my_location);
		locationAddress.setText(R.string.my_location_address);
		popupView.setVisibility(View.GONE);

		// 构建测距工具栏PopView
		View caldisView = LayoutInflater.from(BMap_Distance.this).inflate(
				R.layout.mapframe_caldis, null);
		distancePopView = new PopupWindow(caldisView, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT, false);
		distancePopView.setOutsideTouchable(true);
		distancePopView.setTouchable(true);
		distanceBtn = (Button) caldisView.findViewById(R.id.Button_dis);
		delMarkBtn = (ImageButton) caldisView
				.findViewById(R.id.ImageButton_del);
		delAllMarkBtn = (ImageButton) caldisView
				.findViewById(R.id.ImageButton_remove);
		caldisView.findViewById(R.id.Button_CalDis).setOnClickListener(this);
		distanceBtn.setOnClickListener(this);
		delMarkBtn.setOnClickListener(this);
		delAllMarkBtn.setOnClickListener(this);

		// 构建搜索公交PopView
		View searchView = LayoutInflater.from(BMap_Distance.this).inflate(
				R.layout.navsearch, null);
		searchPopView = new PopupWindow(searchView, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT, true);
		searchPopView.setBackgroundDrawable(new BitmapDrawable());
		searchPopView.setOutsideTouchable(true);
		startAutoComleteTV = (AutoCompleteTextView) searchView
				.findViewById(R.id.autotextview_roadsearch_start);
		endAutoComleteTV = (AutoCompleteTextView) searchView
				.findViewById(R.id.autotextview_roadsearch_start);
		searchBtn = (ImageButton) searchView
				.findViewById(R.id.imagebtn_roadsearch_search);
		searchBtn.setOnClickListener(this);

		navButton.setOnClickListener(this);
		hokeyBtn.setOnClickListener(this);
		mylocBtn.setOnClickListener(this);
		searchTV.setOnClickListener(this);
		zoomUpBtn.setOnClickListener(this);
		zoomDownBtn.setOnClickListener(this);
		trafficTbn.setOnClickListener(this);
		screenshotBtn.setOnClickListener(this);
	}

	/**
	 * [一句话功能简述]<BR>
	 * [功能详细描述]
	 * 
	 * @return
	 * @see com.baidu.mapapi.MapActivity#isRouteDisplayed()
	 */
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	/**
	 * 初始化百度地图组件<BR>
	 * [功能详细描述]
	 */
	public void initMap() {
		WalktourApp walktourApp = (WalktourApp) this.getApplication();
		if (walktourApp.mMapManager == null) {
			walktourApp.mMapManager = new BMapManager(getApplication());
			walktourApp.mMapManager.init(walktourApp.mapKey,
					new WalktourApp.MyGeneralListener());
		}
		walktourApp.mMapManager.start();
		mLocationManager = walktourApp.mMapManager.getLocationManager();
		mkSearch = new MKSearch();
		mkSearch.init(walktourApp.mMapManager, this);
		// mkOfflineMap = new MKOfflineMap();
		// mkOfflineMap.init(walktourApp.mMapManager, this);
		// Logger.e(TAG, "mkOfflineMap.scan():"+mkOfflineMap.scan());
		// 如果使用地图SDK，需初始化地图Activity
		super.initMapActivity(walktourApp.mMapManager);
		mapController = mapView.getController();
		// 我的位置图层
		myLocationOverlay = new MeLocationOverlay(BMap_Distance.this, mapView,
				popupView);
		// 轨迹图层
		Drawable marker = getResources().getDrawable(R.drawable.icon_marka); // 得到需要标在地图上的资源
		locusOverlayItem = new LocusOverlayT(BMap_Distance.this, mapView,
				popupView, marker, mkSearch);
		mapView.addView(popupView, new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null,
				MapView.LayoutParams.TOP_LEFT));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ImageButtonNav:
			mapView.getOverlays().add(locusOverlayItem);
			mapController.animateTo(locusOverlayItem.getmGeoList().get(0)
					.getPoint());
			break;
		case R.id.ImageButtonHotkey:
			break;
		case R.id.ImageButtonMyloc:
			if (locationGeoPoint == null) {
				Toast.makeText(BMap_Distance.this, "正在定位中,请稍后...",
						Toast.LENGTH_LONG).show();
			} else {
				mapController.animateTo(locationGeoPoint);
				mapView.getOverlays().add(myLocationOverlay);
			}
			break;
		case R.id.ImageButtonZoomUp:
			mapController.zoomIn();
			break;
		case R.id.ImageButtonZoomDown:
			mapController.zoomOut();
			break;
		case R.id.ToggleButton_ITS:
			if (trafficTbn.isChecked()) {
				mapView.setTraffic(true);
			} else {
				mapView.setTraffic(false);
			}
			break;
		case R.id.Button_CalDis:
			distancePopView.dismiss();
			mapView.getOverlays().remove(mapView.getOverlays().size() - 1);
			distanceBtn.setText("0.0公里");
			distanceMenuItem.setEnabled(true);
			mapView.invalidate();
			break;
		case R.id.ImageButton_del:
			mDistanceOverlay.clearLatsMark();
			mapView.invalidate();
			break;
		case R.id.ImageButton_remove:
			mDistanceOverlay.clearAllMark();
			mapView.invalidate();
			break;
		case R.id.ImageButtonAR:
			mapView.buildDrawingCache();
			Bitmap bitmap = mapView.getDrawingCache();
			// 获取保存路径
			String externalPath = Environment.getExternalStorageDirectory()
					.getPath();
			String fileName = String.valueOf(System.currentTimeMillis())
					+ ".jpg";
			String savePath = externalPath + "/" + fileName;
			if (bitmap != null) {
				ImageUtil.saveBitmap(bitmap, savePath);
				Builder builder = new AlertDialog.Builder(BMap_Distance.this);
				builder.setTitle("保存为图片");
				builder.setMessage("保存成功,路径:" + savePath);
				builder.setPositiveButton("OK",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				builder.show();
			} else {
				Toast.makeText(BMap_Distance.this, "The Bitmap is null.",
						Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.TextViewSearch:
			searchPopView.showAtLocation(this.getCurrentFocus(), Gravity.TOP,
					0, 38);
			searchPopView.update();
			break;
		case R.id.imagebtn_roadsearch_search:
			// 对起点终点的name进行赋值，也可以直接对坐标赋值，赋值坐标则将根据坐标进行搜索
			MKPlanNode stNode = new MKPlanNode();
			stNode.name = startAutoComleteTV.getText().toString();
			MKPlanNode enNode = new MKPlanNode();
			enNode.name = endAutoComleteTV.getText().toString();
			mkSearch.transitSearch("珠海", stNode, enNode);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onPause() {
		// 移除listener
		mLocationManager.removeUpdates(this);
		myLocationOverlay.disableMyLocation();
		// 打开指南针
		myLocationOverlay.disableCompass();
		WalktourApp.getContext().mMapManager.stop();
		super.onPause();

	}

	@Override
	protected void onResume() {
		Logger.e(TAG, "onResume");
		// 添加listener
		mLocationManager.requestLocationUpdates(this);
		myLocationOverlay.enableMyLocation();
		// 打开指南针
		myLocationOverlay.enableCompass();
		WalktourApp.getContext().mMapManager.start();
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, "离线地图");
		menu.add(1, 2, 2, "测距");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getGroupId()) {
		case 0:
			Intent intent = new Intent(BMap_Distance.this,
					OfflineMapActivity.class);
			startActivity(intent);
			break;
		case 1:// 测距
			mDistanceOverlay = new DistanceOverlay(BMap_Distance.this,
					getResources().getDrawable(R.drawable.icon_marka), this);
			mapView.getOverlays().add(mDistanceOverlay);
			showDistancePopView();
			this.distanceMenuItem = item;
			item.setEnabled(false);
			break;
		case 2:

			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 弹出测距PopWindows<BR>
	 * [功能详细描述]
	 */
	public void showDistancePopView() {
		distancePopView.showAtLocation(this.getCurrentFocus(), Gravity.TOP, 0,
				38);
		distancePopView.update();
	}

	/**
	 * [一句话功能简述]<BR>
	 * [功能详细描述]
	 * 
	 * @param arg0
	 * @param arg1
	 * @see com.baidu.mapapi.MKSearchListener#onGetAddrResult(com.baidu.mapapi.MKAddrInfo,
	 *      int)
	 */
	@Override
	public void onGetAddrResult(MKAddrInfo addrInfo, int arg1) {
		if (addrInfo != null) {
			Logger.i(TAG, addrInfo.strAddr);
			((TextView) popupView.findViewById(R.id.locationAddress))
					.setText(addrInfo.strAddr);
		}
	}

	@Override
	public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {

	}

	@Override
	public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {

	}

	@Override
	public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {

	}

	@Override
	public void onGetTransitRouteResult(MKTransitRouteResult res, int error) {
		if (error != 0 || res == null) {
			Toast.makeText(BMap_Distance.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		TransitOverlay routeOverlay = new TransitOverlay(BMap_Distance.this,
				mapView);
		// 此处仅展示一个方案作为示例
		routeOverlay.setData(res.getPlan(0));
		mapView.getOverlays().clear();
		mapView.getOverlays().add(routeOverlay);
		mapView.invalidate();

		mapView.getController().animateTo(res.getStart().pt);
	}

	@Override
	public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {

	}

	@Override
	public void onGetOfflineMapState(int type, int state) {

	}

	@Override
	public void onLocationChanged(Location location) {
		if (location != null) {
			String strLog = String.format(
					"您当前的位置:\r\n" + "纬度:%f\r\n" + "经度:%f",
					location.getLongitude(), location.getLatitude());
			Logger.i(TAG, strLog);
			if (locationGeoPoint == null) {
				locationGeoPoint = new GeoPoint(
						(int) (location.getLatitude() * 1e6),
						(int) (location.getLongitude() * 1e6));
			} else {
				locationGeoPoint
						.setLatitudeE6((int) (location.getLatitude() * 1e6));
				locationGeoPoint
						.setLongitudeE6((int) (location.getLongitude() * 1e6));
			}
		}
	}

	@Override
	public void onDistanceResult(double result) {
		String resultString = "公里";
		if (result < 1) {
			resultString = ((double) ((int) Math.round(result * 1000 * 10)) / 10.0)
					+ "米";
		} else {
			resultString = ((double) (((int) Math.round(result * 10))) / 10.0)
					+ "公里";
		}
		distanceBtn.setText(resultString);
	}

}